﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using UnityLancher;
using Wox.Plugin;
using Wox.Plugin.Everything.Everything;

namespace WoxUnityPlugin
{
    public class ProjectInfo
    {
        public ProjectInfo(string path, string version)
        {
            this.path = path;
            this.version = version;
        }

        public string path;
        public string version;
    }

    public class Main : IPlugin, IContextMenu
    {
        UnityLancher.UnityLancherCore launcher;

        private UnityProjectFinder projectFinder;

        public void Init(PluginInitContext context)
        {
            launcher = new UnityLancher.UnityLancherCore();
            projectFinder = new UnityProjectFinder();
        }

        public List<Result> LoadContextMenus(Result selectedResult)
        {
            var ret = new List<Result>();
            var project = selectedResult.ContextData as ProjectInfo;

            ret.Add(new Result()
            {
                Title = "Open Project Folder",
                SubTitle = "",
                IcoPath = "Images\\folder.png",
                Action = ac =>
                {
                    Process.Start("explorer", project.path.Replace('/', '\\'));
                    return true;
                }
            });

            var resultList = new List<Result>();

            foreach (var kvp in launcher.versionDict)
            {
                var version = kvp.Key;
                var path = kvp.Value;

                bool isProjectVersion = version == project.version;
                var title = "Open With Unity " + kvp.Key;

                var result = new Result()
                {
                    Title = title,
                    SubTitle = isProjectVersion ? "★★★★★": "",
                    IcoPath = "Images\\app.png",
                    Action = ac =>
                    {
                        var p = WinHelper.GetProcessUsedFile((project.path + "\\Temp\\UnityLockfile"));
                        if (p != null)
                        {
                            p.Kill();   
                        }

                        launcher.OpenProject(project.path, kvp.Key);
                        return true;
                    }
                };

                // 版本匹配则插入到第二个
                if(isProjectVersion && ret.Count > 1)
                {
                    ret.Insert(1, result);
                }
                else
                {
                    ret.Add(result);
                }
            }

            return ret;
        }

        public List<Result> Query(Query query)
        {
            var projects = projectFinder.GetAllProjects();
            var ret = new List<Result>();

            //launcher.InitRecentProjects();

            try
            {
                //var allProjects = new Dictionary<string, string>(launcher.recentProject);
                var allProjects = new Dictionary<string, string>();

                foreach (var kvp in projects)
                {
                    var p = kvp.Key.Replace('\\', '/');
                    if (!allProjects.ContainsKey(p))
                    {
                        allProjects.Add(p, kvp.Value);
                    }
                }

                foreach (var kvp in allProjects)
                {
                    var path = kvp.Key;
                    var version = kvp.Value;
                    var name = Path.GetFileName(kvp.Key);

                    if (!string.IsNullOrEmpty(query.Search))
                    {
                        if (name.IndexOf(query.Search, StringComparison.OrdinalIgnoreCase) < 0)
                        {
                            continue;
                        }
                    }

                    bool hasVersion = launcher.versionDict.ContainsKey(version);
                    var subTitle = "";
                    if(hasVersion)
                    {
                        subTitle = version + " - " + path;
                    }
                    else
                    {
                        subTitle = version + " [Not Installed!] - " + path;
                    }

                    ret.Add(new Result()
                    {
                        Title = Path.GetFileName(kvp.Key),
                        SubTitle = subTitle,
                        IcoPath = "Images\\app.png",
                        Action = ac =>
                        {
                            launcher.OpenProject(path, version);
                            return true;
                        },

                        ContextData = new ProjectInfo(path, version)
                    });
                }
            }
            catch (Exception e)
            {

            }

            return ret;
        }
    }
}
